﻿using System;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace Wawawum.RecycleBinCleaner
{
    public static class Cleaner
    {
        public static bool SiteUrlIsValid(string url)
        {
            if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
            {
                Uri uri = SPUtility.AlternateServerUrlFromHttpRequestUrl(new Uri(url));

                if (SPSite.Exists(uri)) // Dans le cas d'une collection de site
                {
                    return true;
                }
                else // Dans le cas d'un spweb
                {
                    try
                    {
                        using (SPSite site = new SPSite(uri.ToString()))
                        {
                            string siteAbsoluteUrl = site.Url;

                            if (uri.ToString().Contains(siteAbsoluteUrl))
                            {
                                string webUrl = uri.ToString().Remove(0, siteAbsoluteUrl.Length).Trim('/');

                                try
                                {
                                    return site.OpenWeb(webUrl, true).Exists;
                                }
                                catch (Exception)
                                {
                                    return false;
                                }
                            }
                            else
                            {
                                return false;
                            }
                        }
                    }
                    catch (FileNotFoundException)
                    {
                        return false;
                    }
                }
            }
            else
            {
                return false;
            }
        }

        public static void Clean(string url)
        {
            using (SPSite site = new SPSite(url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.RecycleBin.DeleteAll();
                }
            }
        }
    }
}
